	google.load("prototype", "1.7.0.0");
	google.load("scriptaculous", "1.8.3");
	google.load("maps", "3", {other_params: "sensor=false"});
	google.load("gdata", "1");

	// Variablen definieren
	var map;
	var markersArray;	
	var geocoder;
	var deutscheMitte;
	var point;
	var deutschSW;
	var deutschNO;
	var deutscheGrenzen;
	// Copy from Google
	var mtbImage;
	var roadImage;
  	var shadowImage;
	// Create the calendar service object
	var calendarService;
	// The default "private/full" feed is used to insert event to the 
	// primary calendar of the authenticated user
	var calendarScope;
	//URL to DoodleWizard
	var doodleWizard;
	// Cookie values
	var cookieValues;
	// Cookie name
	var cookieName;
	// maps direction url
	var mapsDirectionUrl;
	var dlgStatusBar;
	var dlgConfiguration;

	/**
	 * Initialisiere Variablen
	 */
	function initVars() {
		markersArray = [];
		geocoder = new google.maps.Geocoder();
		// Nord=55.018611 Süd:47.409722 Ost:14.975 West:5.880833 gemaess Wikipedia Recherche
		deutscheMitte = new google.maps.LatLng(51.221944, 9.3875);
		point = deutscheMitte;
		deutschSW = new google.maps.LatLng(47.3, 5.8);
		deutschNO = new google.maps.LatLng(55.1, 15.1);
		deutscheGrenzen = new google.maps.LatLngBounds(deutschSW, deutschNO);
		mtbImage = new google.maps.MarkerImage('mountainbike_green_small.png',
	      new google.maps.Size(22, 26),
	      new google.maps.Point(0,0),
	      new google.maps.Point(0, 13));
		roadImage = new google.maps.MarkerImage('cyclingsport_small.png',
	      new google.maps.Size(22, 26),
	      new google.maps.Point(0,0),
	      new google.maps.Point(0, 13));
	  	shadowImage = new google.maps.MarkerImage('shadow_small.png',
	      new google.maps.Size(36, 26),
	      new google.maps.Point(0,0),
	      new google.maps.Point(0, 13));
		// Create the calendar service object
		calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
		// The default "private/full" feed is used to insert event to the 
		// primary calendar of the authenticated user
		calendarScope = "http://www.google.com/calendar/feeds/default/private/full";
		//URL to DoodleWizard
		doodleWizard = "http://doodle.com/wizard/generalInformation.html?type=date";
		// Cookie values
		cookieValues = [];
		// Cookie name
		cookieName = "de.schoel.radnetserver.location";
		// maps direction url
		mapsDirectionUrl="http://maps.google.de/maps?hl=de&z=10&iwstate1=dir:to&daddr=";
		dlgStatusBar = {
			init : function(a, b) {
				this.obj = a;
				this.c = b;
				this.p = this.obj.up()
			},
			align : function() {
				this.obj.setStyle( {
					opacity : 0.7,
					left : ((this.p.getWidth() - this.obj.getWidth()) / 2) + "px",
					top : ((this.p.getHeight() - this.obj.getHeight()) / 2) + "px"
				})
			},
			status : function(a) {
				this.align();
				this.c.update(a);
				this.obj.show()
			},
			hide : function() {
				this.obj.hide()
			}
		}
		
		dlgConfiguration = {
			init : function (a) {
				this.obj = a;
				this.p = this.obj.up();
			},
			align : function() {
				this.obj.setStyle( {
					opacity : 0.7,
					left : ((this.p.getWidth() - this.obj.getWidth()) / 2) + "px",
					top : ((this.p.getHeight() - this.obj.getHeight()) / 2) + "px"	
				})
			},
			show : function() {
				this.align();
				pCenter = map.getCenter();
				$(configLong).value = pCenter.lng();
				$(configLat).value = pCenter.lat();
				this.obj.show();
			},
			hide : function() {
				this.obj.hide();
			},
			save : function() {
				storeConfiguration();
				this.obj.hide();
			}
		}

	}
	
	function load() {
		initVars();
		dlgStatusBar.init($("statusbar"), $("statusbar_content"));
		dlgStatusBar.status("Loading Map...");
		dlgConfiguration.init($("configuration"));
		map = new google.maps.Map($("map"));
		// Kartenoptionen
		var myOptions = {
	      zoom: 9,
	      //center: new google.maps.LatLng(-33, 151),
	      mapTypeControl: true,
	      mapTypeControlOptions: {
	        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
	      },
	      zoomControl: true,
	      zoomControlOptions: {
	        style: google.maps.ZoomControlStyle.SMALL
	      },
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
		
		map.setOptions(myOptions);			
		// Falls kein Cookie gesetzt wurde, prüfen, ob der Browser was weiß
		if (document.cookie && (! document.cookie.include(cookieName))) {
		  // Try W3C Geolocation (Preferred)
		  if(navigator.geolocation) {
		      navigator.geolocation.getCurrentPosition(function(position) {
		      point = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		    }, function() {
		      //handleNoGeolocation(browserSupportFlag);
	  			   });
	  			}			
		}
		else {
			// es existiert ein Cookie mit Ort
			cookieString = readCookie();
			var latInd=cookieString.indexOf("lat");
			var lng = cookieString.substring(0, latInd);
			var lat = cookieString.substring(latInd+3, cookieString.length);
			if (lat != "" && lng != "") {
				point = new google.maps.LatLng(lat, lng);
			}
		}
		map.setCenter(point);
		map.setZoom(9);
		window.setTimeout("document.searchrtf.update.click()", 1000);
		// map.setZoom(12);
		updateCalendarButtons();
	}
	
	google.setOnLoadCallback(load);
    //<![CDATA[
	

	function storeConfiguration() {
		// store configuration in cookie
		var ablauf = new Date();
		var insiebenTagen = ablauf.getTime() + (7 * 24 * 60 * 60 * 1000);
		pCenter = map.getCenter();
		ablauf.setTime(insiebenTagen);
		document.cookie = cookieName + "=" + pCenter.lng() + 'lat' + pCenter.lat() + "; expires=" + ablauf.toGMTString();
	}

	function readCookie() {
		 var theCookie=""+document.cookie;
		 var ind=theCookie.indexOf(cookieName+"=");
		 if (ind==-1 || cookieName=="") return "";
		 var ind1=theCookie.indexOf(";",ind);
		 if (ind1==-1) ind1=theCookie.length; 
		 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
	}
	
	function calculateGeoPoint(address) {
		var retPoint = null;
		geocoder.geocode({'address':address}, function(geocodeRes) {
			if (geocodeRes.length < 1) {
				if (address.length >= 5) {
					alert("!point");
					return calculateGeoPoint(address.substr(0, 5) + ", Germany");
				} else {
					alert(address + " nicht gefunden");
				}				
			} else {
				// wir nehmen das erste Ergebnis
				point = geocodeRes[0].geometry.location;
				alert("point:" + point.lat());
				retPoint = point;
			}
		});
		alert("retPoint:" + retPoint.lat());
		return retPoint;
	}
	
	function getWeatherUrl(address, datum) {
		var retUrl;
		var heute = date("d.m.Y");
	}
	
	function showAddress(address, itemid, longitude, latitude, url, internetUrl, datum, aDoodleDatum, art) {
		var point;
		if (longitude == null) {
			point = calculateGeoPoint(address);
		} else {
			point = new google.maps.LatLng(latitude, longitude);
		}
		var displayString = "<p class=\"msc_marker\">" + datum + "<BR>" + address + "<BR>" + url + "<BR>" + internetUrl + "</p>";
		map.setCenter(point);
		var marker;
		var infoWindow;		
		if (art == "CTF") {
		    marker = new google.maps.Marker({
        		position: point,
        		map: map,
        		shadow: shadowImage,
        		icon: mtbImage,
        		//shape: shape,
        		title: datum + ":" + address,
        		//zIndex: beach[3],
        		clickable : true
    		});
			//marker = new google.maps.Marker(point, { icon : mtbIcon , clickable : true});
		}
		else {
		    marker = new google.maps.Marker({
        		position: point,
        		map: map,
        		shadow: shadowImage,
        		icon: roadImage,
        		//shape: shape,
        		title: datum + ":" + address,
        		//zIndex: beach[3],
        		clickable : true
    		});
			//marker = new google.maps.Marker(point, { icon : roadIcon , clickable : true});
		}
    	markersArray.push(marker);
    	// Erzeuge InfoWindow
    	infoWindow = new google.maps.InfoWindow({
        	content: displayString
    	});
    	
		var showPermanent = false;
		google.maps.event.addListener(marker, "click", function() {
			if (showPermanent == false) {
				infoWindow.open(map,marker);
				showPermanent = true;
			} else {
				infoWinow.close();
			}
		});
		google.maps.event.addListener(infoWindow, "closeclick", function() {
			showPermanent = false;
		});
		return infoWindow;
	}
	
	function showMarkerInfo(myInfoWindow, myInfo) {
		myInfoWindow.open(map);
	}
	
	function updateMap(plz) {
		var doContinue = true;
		var point;
		if (isNaN(plz) || plz.length != 5) {
			alert('Bitte eine korrekte PLZ eingeben');
			doContinue = false;
		}
		if (doContinue) {
			geocoder.geocode({'address':plz + ",Deutschland"}, function(geocodeRes) {
				if (geocodeRes.length < 1) {
					alert("Adresse nicht gefunden für: " + plz + ",Deutschland");
				} else {
					// wir nehmen das erste Ergebnis
					point = geocodeRes[0].geometry.location;
					if (deutscheGrenzen.contains(point)) {
						map.setCenter(point);
						//var marker = new google.maps.Marker(point);
					    var marker = new google.maps.Marker({
			        		position: point,
			        		map: map
			        		
			    		});
			    		markersArray.push(marker);
						//map.addOverlay(marker);
						reloadRTF();
					}
					else {
						alert("Google findet für " + plz + " keine Adresse in Deutschland!");
					}
				}
			});
		}
		return false;
	}
	
	function extractHRef(link) {
		var indexStart = link.indexOf("href=") + 6;
		var indexEnd = link.indexOf("\" target");
		if (indexEnd < indexStart) {
			indexEnd = link.indexOf(">") - 1;
		}
		var href = link.substr(indexStart, indexEnd - indexStart);
		return href;
	}
	
	function extractText(link) {
		var indexStart = link.indexOf("blank\">") + 7;
		if (indexStart < 7) {
			indexStart = link.indexOf("\">") + 2;
		}
		var indexEnd = link.indexOf("</a>");
		var text = link.substr(indexStart, indexEnd - indexStart);
		return text;
	}
	
	function clearTable() {
		tbl = document.getElementById("Tabelle");
		while (tbl.rows.length > 1) {
			tbl.deleteRow(1);
		}
		
		$("test-accordion").childElements().each(function(item) {
			item.remove();
		});
	}
	
	function zeileEinfuegen(zeile, datum, ort, url, internetUrl, infoWindow, doodleDate) {
		var TR = document.getElementById("Tabelle").insertRow(zeile + 1);
		var curInfoWindow = infoWindow;
		var urlDisplay = replaceHTMLEntities(extractText(url));
		if (urlDisplay == null || urlDisplay.length < 1) {
			urlDisplay = "weitere Infos";
		}
		var internetUrlDisplay = replaceHTMLEntities(extractText(internetUrl));
		var displayString = "<p class=\"msc_marker\">" + datum + "<BR>" + ort + "<BR>" + url + "<BR>" + internetUrl + "</p>";
		var calendarHTML = "<img src='calendar.png' alt='Kalendereintrag vornehmen' class='msc_image'>";
		var routeHTML = "<img src='route.png' alt='Route berechnen' usemap='#routemap" + zeile + "' class='msc_image'> <map name='routemap" + zeile +"' > <area shape='rect' coords='0,0,20,20' href='" + mapsDirectionUrl + ort.replace('<br>', ',+') + "' target='_blank'></map>" ;
		var doodleHTML = "<img src='doodle.png' alt='Doodle Termin' usemap='#doodlemap" + zeile + "' class='msc_image'> <map name='doodlemap" + zeile +"' > <area shape='rect' coords='0,0,20,12' href='" + doodleWizard + "&title=" + urlDisplay.escapeHTML() + "&" + doodleDate + "=0700||0730||0800||0830||0900' " + "target='_blank'></map>" ; 
		var newOrt = ort.replace("<br>", ", ");
	
		
		var accordion_header = new Element('div', { 'class': 'accordion-toggle'});
		var accordion_header_div = new Element('div', { 'class': 'accordion-toggle-text'}).update(datum + ' ' + '<a target="_blank" href=' + extractHRef(url) +'>' + urlDisplay + '</a>' );
		var textWidth =  $("test-accordion").getWidth() - 25;
		accordion_header_div.setStyle({width: textWidth+"px"});
		var accordion_text = new Element('div', { 'class': 'accordion-content'});
		var accordion_toggle_div = new Element('div', { 'class': 'accordion-toggle-text'}).update(newOrt + '<BR>' + '<a target="_blank" href=' + extractHRef(internetUrl) +'>' + internetUrlDisplay + '</a>' ); 
		var accordion_toggle_button = new Element('div', { 'class': 'accordion-toggle-text', 'margin-right': '10px', 'vertical-align':'bottom', 'align':'right'});
		accordion_toggle_button.setStyle({'text-align': 'right', 'width': textWidth+10+"px"});
		accordion_toggle_button.update( calendarHTML + " " + routeHTML + doodleHTML);
		if (curInfoWindow != null) {
			accordion_text.onmouseover = function() {
				showMarkerInfo(curInfoWindow, displayString);
			};
			accordion_text.onmouseout = function() {
				curInfoWindow.close();
			};
		}
		var myImages = accordion_toggle_button.select('[alt="Kalendereintrag vornehmen"]');
		myImages.each(function(item) {
				item.onclick = function() {
				createCalendarEvent(datum, urlDisplay);
			};		
		});
		accordion_header.appendChild(accordion_header_div);
		accordion_text.appendChild(accordion_toggle_div);
		accordion_text.appendChild(accordion_toggle_button);
		$("test-accordion").appendChild(accordion_header);
		$("test-accordion").appendChild(accordion_text);
	}
	
	function replaceHTMLEntities(htmlString) {
		var retVal = htmlString;
		retVal = retVal.replace(/&uuml;/g, "ü");
		retVal = retVal.replace(/&Uuml;/g, "Ü");
		retVal = retVal.replace(/&auml;/g, "ä");
		retVal = retVal.replace(/&Auml;/g, "Ä");
		retVal = retVal.replace(/&ouml;/g, "ö");
		retVal = retVal.replace(/&Ouml;/g, "Ö");
		retVal = retVal.replace(/&szlig;/g, "ß");
		retVal = retVal.replace(/&sz/g, "ß");
		retVal = retVal.replace(/&quot;/g, "\"");
		return retVal;
	}

	// Deletes all markers in the array by removing references to them
	function deleteOverlays() {
	  if (markersArray) {
	    for (var i = 0; i < markersArray.length; i++) {
	      markersArray[i].setMap(null);
	    }
	    markersArray.clear();
	  }
	}
	
	function reloadRTF() {
		dlgStatusBar.status("Lade RTF...");
		bounds = map.getBounds();
		linksUnten = bounds.getSouthWest();
		rechtsOben = bounds.getNorthEast();
		bCTF = $('ctf_cb').checked;
		bMTB = $('mtb_cb').checked;
		if (bMTB || bCTF) {
			deleteOverlays();
			new Ajax.Request("/radnetserver?" + "laMin=" + linksUnten.lat() + "&laMax="
					+ rechtsOben.lat() + "&loMin=" + linksUnten.lng() + "&loMax="
					+ rechtsOben.lng() + "&addMTB=" + bMTB + "&addRR=" + bCTF, {
				method:'get',
  				onSuccess: function(transport) {
  					// Wahrscheinlich ist es besser JSON zu senden und nicht XML
					var curCenter = map.getCenter();
					var xml = transport.responseXML;
					var rtftours = xml.documentElement.getElementsByTagName("rtftour");
					clearTable();
					for ( var i = 0; i < rtftours.length; i++) {
						var datum = rtftours[i].getAttribute("datum");
						var linkUrl = rtftours[i].getAttribute("url");
						var internetUrl = rtftours[i].getAttribute("internetUrl");
						var startort = rtftours[i].getAttribute("startort");
						var art = rtftours[i].getAttribute("art");
						var doodleDatum = rtftours[i].getAttribute("doodledatum");
						var currentInfoWindow = showAddress(startort, rtftours[i]
								.getAttribute("rtfid"), rtftours[i]
								.getAttribute("longitude"), rtftours[i]
								.getAttribute("latitude"), 
								linkUrl, internetUrl, datum, doodleDatum, art);
						zeileEinfuegen(i, datum, replaceHTMLEntities(startort), linkUrl,
								internetUrl, currentInfoWindow, doodleDatum);
					}
					if (rtftours.length < 1) {
						zeileEinfuegen(0,"", "Keine Veranstaltung","","",null,"");
					}
					accordion = new Accordion("test-accordion", 1);
					updateCalendarButtons();
					map.setCenter(curCenter);
					dlgStatusBar.hide();
				}
				}
			);
		}
		else {
			alert("Bitte mindestens CTF oder MTB auswählen");	
			dlgStatusBar.hide();
		}
	}
	
	
	// Calendar Functions
	function logMeIn() {
  		scope = calendarScope;
  		var token = google.accounts.user.login(scope);
  		updateCalendarButtons();
	}
	
	function logMeOut() {
		google.accounts.user.logout();
		updateCalendarButtons();
	}	

	function updateCalendarButtons() {
		var tabellenButtons = $$('.msc_button');
		if (google.accounts.user.checkLogin(calendarScope) == "") {
			for (var i = 0; i < tabellenButtons.length; i++) {
				tabellenButtons[i].disabled = true;
			}
			$(login).disabled = false;
			$(logout).disabled = true;
		}
		else {
			for (var i = 0; i < tabellenButtons.length; i++) {
				tabellenButtons[i].disabled = false;
			}
			$(login).disabled = true;
			$(logout).disabled = false;
		}
	}
	
	function createCalendarEvent(aDatum, aTitle) {
		// The default "private/full" feed is used to insert event to the 
		// primary calendar of the authenticated user
		var feedUri = 'http://www.google.com/calendar/feeds/default/private/full';
		
		// Create an instance of CalendarEventEntry representing the new event
		var entry = new google.gdata.calendar.CalendarEventEntry();
		
		// Set the title of the event
		entry.setTitle(google.gdata.Text.create(aTitle));
		
		// Create a When object that will be attached to the event
		var when = new google.gdata.When();
		
		//parse datum
		var datumTeile = aDatum.split('.');
		var jahr = datumTeile[2];
		// Monatszaehlung beginnt mit 0
		var monat = datumTeile[1] - 1;
		var tag = datumTeile[0];
		
		//JS Dates erstellen
		var jsStartDate = new Date(jahr, monat, tag, 8, 0, 0);
		var jsEndDate = new Date(jahr, monat, tag, 16, 0, 0);
		
		// Set the start and end time of the When object
		var startTime = new google.gdata.DateTime(jsStartDate);
		var endTime = new google.gdata.DateTime(jsEndDate);
		when.setStartTime(startTime);
		when.setEndTime(endTime);
		
		// Add the When object to the event 
		entry.addTime(when);
		
		// The callback method that will be called after a successful insertion from insertEntry()
		var callback = function(result) {
		  //GLog.write('event created!');
		}
		
		// Error handler will be invoked if there is an error from insertEntry()
		var handleError = function(error) {
		  alert(error);
		}
		
		// Submit the request using the calendar service object
		calendarService.insertEntry(feedUri, entry, callback, 
		    handleError, google.gdata.calendar.CalendarEventEntry);		
	}
	
	
    //]]>
